package com.thirtywords.cleaner;

import java.util.List;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.Source;

import com.thirtywords.analizer.Downloader;
import com.thirtywords.analizer.beans.Code;
import com.thirtywords.analizer.beans.Link;

public abstract class Cleaner{
	
	protected final static int MAX_DEEP=1;
	protected Code code;
	protected int deep;
	
	public Cleaner(String url, int deep){
		this.deep=deep;
		this.code=Downloader.getCode(url);
	}
	
	public abstract String doClean();	
	
	public List<Element> getElements(Code code) {

		String body = getBody(code.getOriginalCode());

		Source source = new Source(body);

		return source.getAllElements();

	}

	protected String getBody(String html){
		
		String body=html;
		try{
			if(!html.trim().equals("")){
			
				int begin=html.indexOf("<body");
				int end=html.indexOf("</body");
				
				if(begin>0 && end>0)							
					body=html.substring(begin,end);
			}			
		}catch(StringIndexOutOfBoundsException e){
			//e.printStackTrace();
		}
		return body;		
	}

	protected String removeAttributes(String html){

		String result="";
		
		try{		

			System.out.println("Removing attributes...");
			
			int firstEnd, finalBegin;
			
			System.out.println(html);

			firstEnd=html.indexOf(">");
			
			while(firstEnd!=-1){
				
				System.out.println(html.length());	


				finalBegin=html.indexOf("<");

				html=html.substring(firstEnd+1);
				
				System.out.println(html.length());	
				firstEnd=html.indexOf(">");
			}	
			
			System.out.println(html);				
			
		}catch(StringIndexOutOfBoundsException e){
			e.printStackTrace();
		}
		return result;		
	}
	
	protected void getNextLevel(List<Link> links){

        for(Link link : links){
        	
        	PageCleaner pageCleaner=new PageCleaner(link.getHref(),deep+1);
        		
        	Thread t=new Thread(pageCleaner);
        	t.start();            	
        }
	}
}
